package it.canraid.leaflet.control;

import it.canraid.leaflet.control.activity.DrawActivity;
import it.canraid.leaflet.model.LinePill;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class DrawTextListener implements OnTouchListener {
    private float lastX = -1;
    private float lastY = -1;
    private DrawActivity context;

    public DrawTextListener(DrawActivity context) {
	this.context = context;
    }

    public boolean onTouch(View v, MotionEvent event) {
	switch (event.getAction()) {
	case MotionEvent.ACTION_MOVE:
	    if (!Kernel.R().isRefreshTime())
		return false;

	    float x2 = event.getX();
	    float y2 = event.getY();
	    if (v.getId() == Kernel.ID_DRAW_VIEW) {
		float realLine = Math.abs(x2 - lastX) + Math.abs(y2 - lastY);
		if (realLine < Kernel.REFRESH_DELTA_DRAW)
		    return false;

		Kernel.R().addLine(new LinePill(lastX, lastY, x2, y2));
		lastX = x2;
		lastY = y2;
		v.invalidate();
	    } else if (v.getId() == Kernel.ID_TEXT_VIEW) {
		Kernel.R().setLastInstantPoint(lastX, lastY, x2, v.getLeft() + v.getWidth());
		v.invalidate();
	    }
	    return true;
	case MotionEvent.ACTION_DOWN:
	    lastX = event.getX();
	    lastY = event.getY();
	    if (v.getId() == Kernel.ID_DRAW_VIEW) {
		Kernel.R().addLine(new LinePill(lastX, lastY, lastX, lastY));
		v.invalidate();
	    } else if (v.getId() == Kernel.ID_TEXT_VIEW) {
		Kernel.R().isTextPressed = true;
	    }
	    return true;
	case MotionEvent.ACTION_UP:
	    int aux = 0;
	    if (v.getId() == Kernel.ID_DRAW_VIEW) {
		aux = Kernel.R().storeLineInHistory();
	    } else if (v.getId() == Kernel.ID_TEXT_VIEW) {
		aux = Kernel.R().storeWordInHistory();
		Kernel.R().isTextPressed = false;
	    }
	    if (aux > 0) {
		context.eraseButton.setEnabled(true);
		context.eraseButton.setAlpha(1f);
		v.invalidate();
	    }
	    return true;
	}
	return false;
    }
}
